<?php
namespace Home\Controller;
use Think\Controller;

  
 
class RoomController extends Controller {

    function __construct(){
        parent::__construct();
		
			if (!CheckLogin()) {
		
			//$this->redirect('Home/Login/index', array() , 0, '未登陆，跳转到登陆界面...');
		}       
    }
	
  
    /**
   * 获取周的时间范围
   * @param  Int $type 获取类型，0：本周 1:上周
   * @return Array     返回起止的日期字符串数组
   */
    public function _week_range($type) {
    
		// 当前是星期几，从星期天开始为0
		$now_day_of_week = date('w');
		
		// 计算本周的开始日期
		$current_week_start = date_create();
		$current_week_start->add(date_interval_create_from_date_string('- ' . $now_day_of_week . ' days'));
		$current_week_end = date_create();
		$current_week_end->add(date_interval_create_from_date_string((6 - $now_day_of_week) . ' days'));
		if ($type == 1) {
		  $current_week_start->add(date_interval_create_from_date_string('- 7 days'));
		  $current_week_end->add(date_interval_create_from_date_string('- 7 days'));
		}
		return array(
		  $current_week_start->format('Y-m-d') ,
		  $current_week_end->format('Y-m-d') ,
		);
  }

	//我的房间
	public function index(){	
		$UserId = I('session.menuid');		
		if($UserId){
			$Model = M('tbvcbinformation info');
			$where = "(info.nvcbid IN ( SELECT nroomid FROM tbvcbviceowner viceo WHERE viceo.nuserid = $UserId )) OR info.ncreateid = $UserId";		
			$count = $Model->where($where)->count();
			$items =3;
			$Page = new \Think\Userpage($count,$items);				
			$data = $Model->field('ncreateid,nvcbid,cname')
						  ->where($where)
						  ->limit($Page->firstRow.','.$Page->listRows)	
						  ->select();
			$list = $Page->show(); 	

			$this->assign('data',$data);
			$this->assign('list',$list);				
		}	  	
		$this->display();
	}
	/***
	* 我的广播
	*
	**/
	function myradio(){
		$UserId = I('session.menuid');	
		if($UserId){
			$Model = M('tbroommsg');
			$where['csenduser'] = $UserId;
			$count = $Model->where($where)->count();
			$items =5;
			$Page = new \Think\Userpage($count,$items);	
			$data = $Model->field('dtime,csenduser,nsenduser,ccontent')
						  ->where($where)
						  ->limit($Page->firstRow.','.$Page->listRows)	
						  ->select();
			$list = $Page->show(); 	
			$this->assign('data',$data);
			$this->assign('list',$list);			
		}
	    $this->display();
	}
	
	/***
	* 房间人气
	*
	**/
	function roompopular(){
	
		$roomId = I('get.id');
		if($roomId){						
			$Model = M('tbvcbscoreday');
			$order = "ddate DESC";
			$lastW = $this->_week_range(1);
			$thisW =$this->_week_range(0);
			$today= date('Y-m-d',strtotime("+1 days"));   //当天日期
			
			//上周人气	
			$Lwhere['ddate'] = array('BETWEEN',array($lastW[0],$lastW[1]));	
			$Lwhere['nvcbid'] = $roomId;
			$Lweek = $Model->where($Lwhere)->order($order)->select();
			$Lw_popu = $Model->where($Lwhere)->sum('fscore');
			$this->assign('Lw_popu',$Lw_popu);		
			$this->assign('Lweek',$Lweek);
			
			//本周人气			
			$Twhere['ddate'] = array('BETWEEN',array($thisW[0],$thisW[1]));	
			$Twhere['nvcbid'] = $roomId;
			$Tweek = $Model->where($Twhere)->order($order)->select();
			$Tw_popu = $Model->where($Twhere)->sum('fscore');
			$this->assign('Tw_popu',$Tw_popu);
			$this->assign('Tweek',$Tweek);			
			//本月人气
			
			
			$this_start_month = date('Y-m-01');//本月开始
			
			$tmwhere['ddate'] = array('BETWEEN',array($this_start_month,$today));	
			$tmwhere['nvcbid'] = $roomId;	
			$Tmonth = $Model->where($tmwhere)->order($order)->select();
			$Tm_popu = $Model->where($tmwhere)->sum('fscore');
			$this->assign('Tm_popu',$Tm_popu);			
			$this->assign('Tmonth',$Tmonth);
			
			//上月人气
			$last_start_month = date('Y-m-d',mktime(0,0,0,date('m')-1,1,date('Y')));//上月开始
			$last_end_month = date('Y-m-d',mktime(0,0,0,date('m'),0,date('Y')));//上月结束
			
			$lmwhere['nvcbid'] = $roomId;
			$lmwhere['ddate'] = array('BETWEEN',array($last_start_month,$last_end_month));
			$Lmonth = $Model->where($lmwhere)->order($order)->select();
			$Lm_popu = $Model->where($lmwhere)->sum('fscore');	
			$this->assign('Lm_popu',$Lm_popu);			
			$this->assign('Lmonth',$Lmonth);			
		}		
		$this->display();			
	}
	
	/***
	* 修改房间表单提交 
	*
	**/	
	function oper(){
		$roomId =I('session.roomId');
		$where['nvcbid'] = $roomId;
		$Model = M('tbvcbinformation');
		if($_POST){			
		   $cimage = $this->_upload(); 		   
		   if(!empty($cimage)){
			$data['image'] = RealUrl(C('SITE_BASE_PATH') . $cimage['savepath'] . $cimage['savename']);
		   }		   	   
	   $fu = I('post.fu');
	 
	   if($fu){
		   $nui_fu = array_unique($fu);
			 $url = U('modify'); 		    
			$A = M('tbuseraccount');
			$O=M('tbvcbviceowner');	
			$delet['nroomid'] = $roomId;
			$O->where($delet)->delete();	
			foreach($nui_fu as $val){	
				if(!empty($val)){
				$find['nuserid']=$val;
				$fucount = $A->where($find)->count();
				if(!$fucount){
					$str = '用户'.$val.'不存在';
					 echo "<script>alert('$str');window.location.href='$url';</script>";
					 return;
					 break;
				}else{
					$infor['nroomid'] = $roomId ;
					$infor['nuserid'] = $val ;
					$O->add($infor);						
				}
				
				}			
			}
	   };
		
	   $data['cname'] = I('post.cname');
	   $data['nmictime'] = I('post.maxtime',0,'int');
	   $data['nmaxwaitmic'] = I('post.maxcount',0,'int');
	   $data['cdescription'] = I('post.cdescription');
	   $data['cbroadinfo'] = I('post.cradio');	   	   
	   $result = $Model->where($where) ->save($data);	   
	   if($result){
	  
	    echo "<script>alert('保存成功');window.location.href='$url'</script>";
	   }
	   
	   
	
	}
	}
	
	
	/***
	* 修改房间
	*
	**/
	function modify(){
	
	$roomId = I('get.id');	
	session('roomId',$roomId);
	
	if(!$roomId){
		$roomId =I('session.roomId');
	}
	$UserId = I('session.menuid');	
	$Model = M('tbvcbinformation');
	$shizhu = 0;  //是否是室主
	$where['nvcbid'] = $roomId;
	$roomInfor = $Model->field('image,dcreatetime,ncreateid,dendtime,nseats,nmaxmgr,cname,nmictime,nmaxwaitmic,cdescription,cbroadinfo')
					   ->where($where)
					   ->find();
	$managerCount = M('tbvcbmanager')->where('nroomid='.$roomId)->count();   //房间已有管理人数
	if($roomInfor){
		if($roomInfor['ncreateid']==$UserId){
			$shizhu = 1;
			
			$O=M('tbvcbviceowner');	
			$fudata = $O->field('distinct nuserid,nroomid')->where("nroomid=$roomId")->select();
			$fucount = count($fudata);
			$fulenth = 6;   //副室主个数
			if($fucount>=0&&$fucount<$fulenth){
				for($i=0;$i<$fulenth-$fucount;$i++){
				$fudata[$fulenth-$i]['nuserid'] = '';
				$fudata[$fulenth-$i]['nroomid'] = 0;
				}
			}
			
			$this->assign('fudata',$fudata);
		}
		
		$roomInfor['managerCount']=$managerCount;
		$roomInfor['ifshizhu'] = $shizhu;
	}
	
	$this->assign('roomInfor',$roomInfor);
	


	
	$this->display();
	}

	
	/***
	* 房间图像上传
	*
	**/
	function _upload(){
    $config = array(
      'maxSize' => 500*1024,
      'savePath' => C('UPLOAD') ,
      'rootPath' => './',
      'hash' => false,
      'saveName' => array(
        'uniqid',
        ''
      ) ,
      'exts' => array(
        'jpg',
        'gif',
        'png',
        'jpeg'
      ) ,
      'autoSub' => true,
      'subName' => array(
        'date',
        'ym'
      ) ,
    );
    // 实例化上传类
    $upload = new \Think\Upload($config);
	if(!empty($_FILES['cimage']['name'])){
	
		$size =  getimagesize($_FILES['cimage']['tmp_name']);
		$width = $size[0];
		$height =  $size[1];
		$maxWidh=500;
		$maxHeight = 500;
		if($width>$maxWidh){
			return $this->error('图片宽度不能超过500像素');
		}
		if($height>$maxHeight){
			return $this->error('图片高度不能超过500像素');
		}		
	 
    $cimage = $upload->uploadOne($_FILES['cimage']);
	

	if(!$cimage){
	 $this->error($upload->getError());
	 }
   
	}
	 return $cimage;	
	
	}
	


	//上麦记录
	public function wheat(){
		$UserId = I('session.menuid');
		if($UserId){

			$default_begin_time = date("Y-m-d",strtotime("-3 Days")); 
			$default_end_time =date("Y-m-d",time());
			$startTime = I('get.start_date',$default_begin_time);		
			$preSevenDays = strtotime("-7 Days");
			
			if(strtotime($startTime)<$preSevenDays){
				$startTime = date("Y-m-d", $preSevenDays); 
			}
			
			$endTime = I('get.end_date',$default_end_time);
			
			if(strtotime($endTime)>time()){
				$endTime = $default_end_time; 
			}	
			
			$M = M('tbusermictimeday');
			$where['nuserid'] =$UserId  ;			
			$where['ddate'] = array('BETWEEN',array($startTime,$endTime));	
			$count =$M->where($where)->count();
			$items =15;
			$Page = new \Think\Userpage($count,$items);			
			$data = $M->field('ddate,nminute')
					  ->where($where)
					  ->limit($Page->firstRow.','.$Page->listRows)	
					  ->select();
					  
			$sum = $M->where($where)->sum('nminute');		
			$listshow = $Page->show(); 
			
			$this->assign('list',$listshow);
			$this->assign('startTime',I('get.start_date',$default_begin_time));
			$this->assign('data',$data);
			$this->assign('sum',$sum);
			$this->assign('endTime',I('get.end_date',$default_end_time));
		}			
			$this->display(); 

	}
	
	//上麦详情
	public function wheatinfor(){
		$UserId = I('session.menuid');
		if($UserId){
			$M=M('tbusermictime');		
			$time = I('get.time');		
			$date = date("Y-m-d",strtotime("$time +1 days")); 
			$where['dtime'] = array('BETWEEN',array($time,$date));
			$where['nuserid'] =$UserId  ;	
			$count =$M->where($where)->count();
			$items =15;
			$Page = new \Think\Userpage($count,$items);			
			$data = $M->field('nroomid,dtime,nminute')
					  ->where($where)
					  ->limit($Page->firstRow.','.$Page->listRows)	
					  ->select();		
			$listshow = $Page->show(); 
			$this->assign('list',$listshow);
			$this->assign('data',$data);
		}		
		
		$this->display(); 
	}
	
	
}